//app.js
import api from 'utils/api';

App({
  onLaunch: function () {
    this.login();
  },
  login: function () {
    console.log("用户登录")
    let that = this; 
    var token = wx.getStorageSync('sessionId');
    if (token) {
      console.log("token存在,请求用户信息")
      that.getUserInfo(token);
      return;
    }
    console.log("token不存在,请求用户信息")
    wx.login({
      success: function (res) {
        var code = res.code;
        wx.request({
          url: api.loginUrl,
          data: {
            code: code
          },
          success: function (res) {
            console.log(res)
            wx.setStorageSync('sessionId', res.data.data.sessionId)
            if (res.data.errorCode === 0 && res.data.data.first === true) {
              // 注册
              console.log("用户第一次访问,注册")
              that.registerUser(code,res.data.data.sessionId);
              return;
            }
            if (res.data.errorCode === 0 && res.data.data.first === false) {
              console.log("用户非第一次访问,获取用户信息")
              that.getUserInfo(res.data.data.sessionId);
              return;
            }
            if (res.data.errorCode != 0) {
              // 登录错误
              wx.hideLoading();
              wx.showModal({
                title: '提示',
                content: '无法登录，请重试',
                showCancel: false
              })
              return;
            }
          }
        })
      }
    })
  },
  getUserInfo: function(token) {
    console.log("通过token获取用户信息")
    var that = this;
    wx.request({
      url: api.getUserUrl,
      header: {
        'content-type': 'application/json',
        'x-auth-token': token
      },
      success: function (res) {
        if (res.data.errorCode != 0) {
          console.log("token过期,删除sessionId重新登录")
          wx.removeStorageSync('sessionId')
          that.login();
        } else {
          console.log("通过token请求用户成功")
          that.setUserInfo(res.data.data);
        }
      }
    })
  },
  registerUser: function (code, sessionId) {
    wx.setStorageSync('sessionId', sessionId)
    var that = this;
    wx.getUserInfo({
      success: function (res) {
        var iv = res.iv;
        var encryptedData = res.encryptedData;
        // 下面开始调用注册接口
        wx.request({
          url: api.postUserUrl,
          method: 'POST',
          header: {
            'content-type': 'application/json',
            'x-auth-token': sessionId
          },
          data: {
            code: code,
            encryptedData: encryptedData,
            iv: iv
          },
          success: (res) => {
              if(res.data.errorCode === 0) {
                console.log("注册成功返回")
                wx.hideLoading();
                wx.setStorageSync('sessionId', sessionId)
                that.setUserInfo(res.data.data);
              }
          }
        })
      },
      fail: function (userError) {
        // that.login()
        if (userError.errMsg == 'getUserInfo:fail scope unauthorized' || userError.errMsg == 'getUserInfo:fail auth deny' || userError.errMsg == 'getUserInfo:fail:scope unauthorized' || userError.errMsg == 'getUserInfo:fail:auth deny') {
          console.log("调用getUserInfo失败,跳到auth页面")
          wx.navigateTo({
            url: '/pages/auth/auth'
          })
        } else {
          //之前获取用户信息失败的逻辑代码
        }
      }
    })
  },
  setUserInfo: function (userInfo) {
    this.globalData.userInfo = userInfo;
  },
  globalData: {
    userInfo: null,
    defaultLunboData: [
      {
        id: 1,
        imgUrl: 'http://img02.tooopen.com/images/20150928/tooopen_sy_143912755726.jpg'
      }, {
        id: 2,
        imgUrl: 'http://img06.tooopen.com/images/20160818/tooopen_sy_175866434296.jpg'
      }, {
        id: 3,
        imgUrl: 'http://img06.tooopen.com/images/20160818/tooopen_sy_175833047715.jpg'
      }
    ]
  }
})
